package com.kye.express.business.personal_my_bill.Bill.list;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuItem;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.support.v7.widget.RxToolbar;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.databinding.ActivityBillListBinding;
import com.kye.express.utils.PhoneUtils;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.SlideBar;
import com.kye.express.view.ToastManager;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.bean.bill.BillListBean;
import com.kye.model.bean.bill.MonthlyBalanceBillBean;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.List;
import java.util.Map;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.MultiTypeAdapter;

public class BillListActivity extends BaseAppCompatActivity implements BillListContract.BillListView {

    private static final String KEY_MONTHLY_BALANCE_BILL = "KEY_MONTHLY_BALANCE_BILL";

    private ActivityBillListBinding mBinding;
    private MultiTypeAdapter mAdapter;
    private BillListContract.BillListPresenter mPresenter;
    private BillViewBinder mBinder;
    private MonthlyBalanceBillBean mMonthlyBalanceBillBean;
    private Dialog mProgressDialog;
    private MaterialDialog mDialog;
    private Map<String, Integer> mNavigators;
    private LinearLayoutManager mLinearLayoutManager;

    public static void startActivity(Context context, MonthlyBalanceBillBean bean) {
        context.startActivity(
                new Intent(context, BillListActivity.class)
                        .putExtra(KEY_MONTHLY_BALANCE_BILL, bean)
        );
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_bill_list);

        initView();
        initEvent();
        initData();
    }

    private void initView() {
        mLinearLayoutManager = new LinearLayoutManager(this);
        mBinding.recyclerViewContent.setLayoutManager(mLinearLayoutManager);
        mBinding.recyclerViewContent.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                .margin((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics()), 0)
                .color(R.color.divider)
                .size((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0.1F, getResources().getDisplayMetrics()))
                .build());
        mAdapter = new MultiTypeAdapter();
        mAdapter.setHasStableIds(true);
        mBinder = new BillViewBinder();
        mAdapter.register(BillListBean.BillBean.class, mBinder);
        mBinding.recyclerViewContent.setAdapter(mAdapter);
    }

    private void initEvent() {
        ToolbarManager.setToolbar(this, mBinding.toolbar);

        RxToolbar.itemClicks(mBinding.toolbar)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<MenuItem>() {
                    @Override
                    public void accept(MenuItem menuItem) throws Exception {
                        mPresenter.callToFinance();
                    }
                });

        RxView.clicks(mBinding.linearLayoutErrorNet.btErrorNetRetry)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mBinding.statusLayout.showLoadingView();
                    }
                });

        RxView.clicks(mBinding.linearLayoutErrorServer.btErrorServerRetry)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mBinding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(mBinding.linearLayoutEmpty.btEmptyRetry)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mBinding.statusLayout.showLoadingView();
                    }
                });

        mBinding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                mPresenter.load(mMonthlyBalanceBillBean);
            }
        });

        mBinding.slideBar.setOnTouchLetterChangeListenner(new SlideBar.OnTouchLetterChangeListenner() {
            @Override
            public void onTouchLetterChange(boolean isTouch, String letter, float x, float y) {
                final Integer integer = mNavigators.get(letter);

                mLinearLayoutManager.scrollToPositionWithOffset(integer, 0);

                mBinding.setDay(letter);

                mBinding.setShowBubble(isTouch);
            }
        });
    }

    private void initData() {
        mPresenter = new BillListContract.BillListPresenter();
        mPresenter.bind(this);

        mMonthlyBalanceBillBean = (MonthlyBalanceBillBean) getIntent().getSerializableExtra(KEY_MONTHLY_BALANCE_BILL);
        mBinding.setMonthlyBalanceBillBean(mMonthlyBalanceBillBean);

        mBinding.statusLayout.showLoadingView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_monthly_balance_bill_detail, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
        if (mProgressDialog != null && mProgressDialog.isShowing()) mProgressDialog.dismiss();
    }

    @Override
    public void onError() {
        mBinding.statusLayout.showErrorNetworkView();
    }

    @Override
    public void onError(String msg) {
        mBinding.statusLayout.showErrorServerView();
    }

    @Override
    public void onLoading() {
        mBinding.statusLayout.showLoadingView();
    }

    @Override
    public void onLoaded() {

    }

    @Override
    public void onNavigators(List<String> keyList, Map<String, Integer> navigators) {
        mBinding.slideBar.setLetters(keyList.toArray(new String[]{}));
        mNavigators = navigators;

        mBinding.setSlideBar(keyList.size() > 1);
    }

    @Override
    public void onLoadedData(BillListBean billListBean) {
        mBinding.statusLayout.showContentView();

        mBinding.slideBar.requestLayout();

        mBinding.setBean(billListBean.getTotal());

        mAdapter.setItems(billListBean.getAccountBillDtl());
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onActionLoading() {
        mProgressDialog = KyeProgressDialog.show(this, mProgressDialog);
    }

    @Override
    public void onCallToFinance(String financePhone) {
        if (mDialog == null) {
            mDialog = new MaterialDialog.Builder(BillListActivity.this)
                    .title("温馨提示")
                    .content("是否拨打财务电话")
                    .positiveText("确认拨打")
                    .negativeText(R.string.common_cancel)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            PhoneUtils.call(BillListActivity.this, financePhone);
                        }
                    })
                    .build();
        }
        mDialog.show();
    }

    @Override
    public void onActionError(String msg) {
        ToastManager.show(this, msg);
    }

    @Override
    public void onActionError() {
        ToastManager.show(this, R.string.common_net_error);
    }

    @Override
    public void onActionLoaded() {
        mProgressDialog.dismiss();
    }
}
